/**
 * @author xxqin
 * @date 2017-07-02
 * @description:通用方法  操作数组、对象等
 * */
var uploaderLinlk = {};
var common = (function (_self) {
  //常用正则
  //手机号验证
  _self.isMobile = function (value) {
    return (value.length == 11 && /^1[3578]\d{9}$/.test(value)) ? true : false;
  }
  //符合要求的用户名
  _self.RegExp_userName = function (value) {
    return (value.length > 0 && value.length < 30 && /^[A-Za-z0-9]+$/.test(value)) ? true : false;
  }
  //符合要求的密码
  _self.RegExp_password = function (value) {
    return (value.length > 0 && value.length < 30 && /^[A-Za-z0-9]+$/.test(value)) ? true : false;
  }
  /*====================================从这里开始是时间转换和操作的相关方法===================================================*/
  //时间位数为1位数时，前面补0
  _self.setFormat = function (x) {
    if (x < 10) {
      x = "0" + x;
    }
    return x;
  }

  //时间戳转换(yyyy-mm-dd hh:mm:ss)
  _self.transtimestamp = function (timestamp) {
    if (timestamp === null || timestamp === '' || timestamp == undefined) {
      return '-';
    }
    if (typeof (timestamp) == "string") {
      return timestamp;
    }
    if (typeof (timestamp) == "number" && timestamp.toString().length != 13) { //这里只处理13位的标准时间戳
      return timestamp;
    }
    var date = new Date(timestamp);
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = _self.setFormat(date.getDate()) + ' ';
    h = _self.setFormat(date.getHours()) + ':';
    m = _self.setFormat(date.getMinutes()) + ':';
    s = _self.setFormat(date.getSeconds());
    return (Y + M + D + h + m + s);
  }


  //时间戳转换(yyyy-mm-dd)
  _self.transtimestampYMD = function (timestamp) {
    if (timestamp == null || timestamp == '') {
      return '';
    }
    var date = new Date(timestamp);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = _self.setFormat(date.getDate());
    return (Y + M + D);
  }
  //截取"2017-08-30 00:00:00" ==> "2017-08-30"
  _self.NewDateYMD = function (str) {
    if (str == null || str == '') {
      return '';
    }
    str = str.split(" ")[0];
    return str;
  }
  // "date": "2016-08-31 00:00:00" 转时间戳
  _self.transtimeTostamp = function (timestamp) {
    if (timestamp == null || timestamp == '') {
      return '';
    }
    var date = new Date(timestamp);
    var time = date.getTime();
    return (time);
  }
  //yyyy-mm-dd hh:mm:ss
  _self.getNowtime = function () {
    var date = new Date(); //日期对象
    var now = "";
    now = date.getFullYear() + "-"; //读英文就行了
    now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; //取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + _self.setFormat(date.getDate()) + " ";
    now = now + _self.setFormat(date.getHours()) + ":";
    now = now + _self.setFormat(date.getMinutes()) + ":";
    now = now + _self.setFormat(date.getSeconds()) + "";
    return now;
  }
  //yyyy-mm-dd hh:mm:ss
  _self.getTimeToyyyymmddhhmm = function (timeStr) {
    if (timeStr == null || timeStr == "") {
      return '';
    }
    var timeArr = timeStr.split(':');
    return timeArr[0] + ":" + timeArr[1];
  }
  //20170718221057
  _self.getNowtimeForCallEquip = function () {
    var date = new Date(); //日期对象
    var now = "";
    now = date.getFullYear().toString(); //读英文就行了
    now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1).toString(); //取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + _self.setFormat(date.getDate()).toString();
    now = now + _self.setFormat(date.getHours()).toString();
    now = now + _self.setFormat(date.getMinutes()).toString();
    now = now + _self.setFormat(date.getSeconds()).toString();
    return now;
  }
  //yyyy-mm-dd
  _self.getNowtimeYMD = function () {
    var date = new Date(); //日期对象
    var now = "";
    now = date.getFullYear() + "-"; //读英文就行了
    now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; //取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + _self.setFormat(date.getDate());
    return now;

  }
  //yyyymmdd
  _self.getNowtimeYMDNoLine = function () {
    var date = new Date(); //日期对象
    var now = "";
    now = date.getFullYear().toString(); //读英文就行了
    now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1).toString(); //取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + _self.setFormat(date.getDate()).toString();
    return now;

  }
  //获取从现在到 AddDayCount 天前的时间 
  /*document.write("前天："+GetDateStr(-2)); 
  document.write("<br />昨天："+GetDateStr(-1)); 
  document.write("<br />今天："+GetDateStr(0)); 
  document.write("<br />明天："+GetDateStr(1)); 
  document.write("<br />后天："+GetDateStr(2)); 
  document.write("<br />大后天："+GetDateStr(3)); */
  _self.GetDateStr = function (AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期 
    var y = dd.getFullYear();
    var m = _self.setFormat(dd.getMonth() + 1); //获取当前月份的日期 
    var d = _self.setFormat(dd.getDate());
    return y + "-" + m + "-" + d;
  }
  //获取从beginTime到 AddDayCount 天前的时间  beginTime是个时间戳
  _self.timestampSomeDaysAgo = function (beginTime, AddDayCount) {
    var dd = new Date(beginTime);
    dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期 
    var now = "";
    now = dd.getFullYear() + "-"; //读英文就行了
    now = now + (dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1) + '-'; //取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + _self.setFormat(dd.getDate()) + " ";
    now = now + _self.setFormat(dd.getHours()) + ":";
    now = now + _self.setFormat(dd.getMinutes()) + ":";
    now = now + _self.setFormat(dd.getSeconds()) + "";
    return now;
  }
  //获取从现在到 beforetime 小时前的时间 
  _self.beforeNowtime = function (beforetime) {
    var date = new Date(); //日期对象
    date.setHours(date.getHours() - beforetime);
    var now = "";
    now = date.getFullYear() + "-"; //读英文就行了
    now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; //取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + _self.setFormat(date.getDate()) + " ";
    now = now + _self.setFormat(date.getHours()) + ":";
    now = now + _self.setFormat(date.getMinutes()) + ":";
    now = now + _self.setFormat(date.getSeconds()) + "";
    return now;
  }
  //获取从现在到 beforetime 分钟前的时间
  _self.beforeNowtimeByMinu = function (beforetime) {
    var date = new Date(); //日期对象
    date.setMinutes(date.getMinutes() - beforetime);
    var now = "";
    now = date.getFullYear() + "-"; //读英文就行了
    now = now + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; //取月的时候取的是当前月-1如果想取当前月+1就可以了
    now = now + _self.setFormat(date.getDate()) + " ";
    now = now + _self.setFormat(date.getHours()) + ":";
    now = now + _self.setFormat(date.getMinutes()) + ":";
    now = now + _self.setFormat(date.getSeconds()) + "";
    return now;
  }


  /*================================从这里开始是checkbox=======================================================*/
  //多个radio，根据第一个参数name全部不选，根据第二个参数id选中哪个
  _self.selectedRadio = function (radioName, radioId) {
    $("input[name='" + radioName + "']").removeAttr("checked");
    $("#" + radioId).attr("checked", true).prop("checked", true);
  }
  /*================================从这里开始是array、string操作相关的方法========================================================*/
  //删除数组中某个元素  eg: deleteArrByEle(emp,"fd")
  _self.deleteArrByEle = function (arr, ele) {
    var index = arr.indexOf(ele);
    if (index > -1) {
      arr.splice(index, 1);
    }
    return arr;
  }


  /**
   * 后端非法数据格式化
   * 
   */
  //把后端传来的null或对象的undefined属性转为""
  _self.transNullundefined = function (a) {
    if (a == null || a == undefined) {
      return "";
    } else {
      return a;
    }
  }
  _self.transNullundefinedToline = function (a) {
    if (a == null || a == undefined || a == "") {
      return "-";
    } else {
      return a;
    }
  }

  /**
   * 后端非法数据格式化为0
   * 
   */
  //把后端传来的null或对象的undefined属性转为"0"
  _self.transNullundefinedToZero = function (a) {
    if (a == null || a == undefined) {
      return 0;
    } else {
      return a;
    }
  }

  //显示默认图片
  _self.transDefaultImg = function (a) {
    if (a == null || a == undefined || a == "") {
      return staticPath + "img/emptyImg/imgnone.png";
    } else {
      return a;
    }
  }
  //显示默认图片---巡检
  _self.transDefaultImg_check = function (a) {
    if (a == null || a == undefined || a == "") {
      return staticPath + "img/emptyImg/default_check.png";
    } else {
      return a;
    }
  }
  //有onclick传对象参的html片段要小心使用
  _self.transHtmlillegal = function (html) {
    var html = html.replace(/undefined|null/gm, "");
    return html;
  }
  /**
   * 获取指定元素的index
   * @param {Array} array 数组
   * @param {object} param 数组中的元素
   */
  _self.isChildOfArray = function (array, param) {
    var index,
      markFlag = false;

    if (common.type(array) != "array") {
      console.error("param is not a Array");
      return;
    }

    index = array.length;
    while (index--) {
      if (array[index] === param) {
        return index;
      }
    }
    return -1;
  }

  /*
   *form表单相关操作
   */
  _self.formclear = function ($form) {
    $(':input', $form)
      .not(':button, :submit, :reset') //, :hidden
      .val('')
      .removeAttr('checked')
      .removeAttr('selected');
    //$form.find("select.select2").prop('selectedIndex', 0).select2().trigger("change");
  }

  /**
   * 将表单域转化成Json对象
   * @memberOf {jQuery} form
   * @return {Object} Json对象
   */
  _self.serializeObject = function ($from) {
    var o = {};

    $(":input", $from).each(function () {
      var type = this.type,
        tag = this.tagName.toLowerCase(), // normalize case
        name = this.name,
        value = this.value; //要trim

      // 移除空的checkbox和radio
      if ((type === 'checkbox' || type === 'radio') && !this.checked) {
        return true; // 如果return true 就相当于continure
      }

      if (name) {
        if (o[name]) {
          if (!o[name].push) {
            o[name] = [o[name]];
          }
          o[name].push(value || '');
        } else {
          o[name] = value || '';
        }
      }
    });
    return o;
  }

  /*=============================从这开始是通用配置==============================================*/
  //判断浏览器厂家(不是内核)和版本  返回 Chrome: 62.0.3202.75
  _self.getBrowserAttr = function () {
    var Sys = {};
    var ua = navigator.userAgent.toLowerCase();
    var s;
    (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
      (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
        (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
          (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
            (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;

    //以下进行测试
    if (Sys.ie) return ('IE: ' + Sys.ie);
    if (Sys.firefox) return ('Firefox: ' + Sys.firefox);
    if (Sys.chrome) return ('Chrome: ' + Sys.chrome);
    if (Sys.opera) return ('Opera: ' + Sys.opera);
    if (Sys.safari) return ('Safari: ' + Sys.safari);
  }

  //生成一个指定长度的字符串
  _self.createString = function (length) {
    var d,
      e,
      b = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
      c = "";
    for (d = 0; length > d; d += 1)
      e = Math.random() * b.length, e = Math.floor(e), c += b.charAt(e);
    return c;
  }
  //用法：$("#"+escapeJquery(id))
  //适用：当id含有特殊字符的时候，是不能选中的
  _self.escapeJquery = function (srcString, removeSpace) {
    // 转义之后的结果
    var escapseResult = srcString;

    // javascript正则表达式中的特殊字符
    var jsSpecialChars = ["\\", "^", "$", "*", "?", ".", "+", "(", ")", "[",
      "]", "|", "{", "}"
    ];

    // jquery中的特殊字符,不是正则表达式中的特殊字符
    var jquerySpecialChars = ["~", "`", "@", "#", "%", "&", "=", "'", "\"",
      ":", ";", "<", ">", ",", "/"
    ];

    for (var i = 0; i < jsSpecialChars.length; i++) {
      escapseResult = escapseResult.replace(new RegExp("\\" +
        jsSpecialChars[i], "g"), "\\" +
      jsSpecialChars[i]);
    }

    for (var i = 0; i < jquerySpecialChars.length; i++) {
      escapseResult = escapseResult.replace(new RegExp(jquerySpecialChars[i],
        "g"), "\\" + jquerySpecialChars[i]);
    }
    if (removeSpace) {
      escapseResult = escapseResult.replace(/\s/g, '');
    }
    return escapseResult;
  }


  //doom相关操作
  /**
   * 设置指定元素获取焦点
   * @param {Object} $dom jQuery对象
   */
  _self.setFocus = function ($dom) {
    var value;
    if (!$dom.length) {
      return;
    }
    value = $dom.val();
    if (value) {
      $dom.val("").focus().val(value);
    } else {
      $dom.focus();
    }
  };

  //获取url总的参数
  _self.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null && unescape(r[2]) != "undefined") return unescape(r[2]);
    return null; //返回参数值 //中文需要 escape("最后二次上传") 先这样加密
  }

  //获取项目根路径的方法
  _self.getRootPath = function () {
    var curPageUrl = window.document.location.href;
    var rootPath = curPageUrl.split("//")[0] + "//" + curPageUrl.split("//")[1]
      .split((native.getDataByKey("IS_OFFLINE_MODULE") == "1") ? "ilink-app-h5-zd" : "/")[0];
    return rootPath;
  }
  //获取时间显示
  _self.getTimeShow = function (timeData) {
    var timedata = timeData.toString();
    var year = timedata.substring(0, 4);
    var month = timedata.substring(4, 6);
    var date = timedata.substring(6, 8);
    var hour = timedata.substring(8, 10);
    var minute = timedata.substring(10, 12);
    var myDate = new Date();
    var showDate = "";
    if (year != myDate.getFullYear()) {
      showDate = year + "年" + month + "月" + date + "日";
    } else if (month != (myDate.getMonth() * 1 + 1)) {
      showDate = month + "月" + date + "日";
    } else if (date != myDate.getDate()) {
      showDate = myDate.getDate() * 1 - date * 1;
      if (showDate == 1) {
        showDate = "昨天";
      } else if (showDate == 2) {
        showDate = "前天";
      } else if (showDate <= 7) {
        showDate = showDate + "天前";
      } else {
        showDate = month + "月" + date + "日";
      }
    } else if (hour != myDate.getHours()) {
      showDate = myDate.getHours() * 1 - hour * 1;
      if (showDate == 1) {
        showDate = myDate.getMinutes() * 1 - minute * 1 + 60;
        showDate = showDate + "分钟之前";
      } else if (showDate > 1 && showDate <= 6) {
        showDate = showDate + "小时之前";
      } else {
        showDate = hour + ":" + minute;
      }
    } else if (minute != myDate.getMinutes()) {
      showDate = myDate.getMinutes() * 1 - minute * 1;
      showDate = showDate + "分钟之前";
    }
    return showDate;
  }


  //引入外部js
  _self.importJs = function (jsUrl, position) {
    var s = document.createElement("script");
    s.src = jsUrl;
    if (position && document[position]) {
      document[position].appendChild(s);
    } else {
      document.head.appendChild(s);
    }
  }
  //根据网络状况进行上传图片
  _self.uploadImage = function (successCb, multiple, fileNumber, container, browse_button, maxSize, fileName, fileType) {
    let isOffline = native.getDataByKey("IS_OFFLINE_MODULE");
    if (isOffline == 1) {
      _self.upload_qiniu_offLine(function (sourceLink, file) {
        successCb && successCb(sourceLink, file);
      }, multiple, fileNumber, container, browse_button, null, null, null, fileType)
      return
    }
    _self.upload_qiniu(function (sourceLink, file) {
      successCb && successCb(sourceLink, file);
    }, multiple, fileNumber, container, browse_button, null, null, null, fileType)
  }

  //上传文件
  _self.upload_qiniu = function (successCb, multiple, fileNumber, container, browse_button, maxSize, fileName, fileType) {
    Dao.qnToken({
      userName: userInfor.accountName,
      deviceId: appKeyObj.deviceId,
    }, function (token) {
      jQuery("#" + container ? container : "upLoadImagesContainer").off();
      jQuery("#" + (container ? container : "upLoadImagesContainer") + " .moxie-shim.moxie-shim-html5").remove();
      jQuery("#" + browse_button ? browse_button : "upLoadPickfiles").off();
      var filetypes = [];
      if (fileType) {
        filetypes = filetypes.concat(fileType);
      } else {
        filetypes.push({
          title: "ilinkPic",
          extensions: "*"
        });
      }
      var max_file_size = "100mb";
      if (maxSize) {
        max_file_size = maxSize;
      }
      var isOver = false;
      uploaderLinlk = Qiniu.uploader({
        runtimes: 'html5,flash,html4', //上传模式,依次退化
        browse_button: browse_button ? browse_button : 'upLoadPickfiles', //上传选择的点选按钮，**必需**
        uptoken: token, //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        domain: QINIUPATH, //bucket 域名，下载资源时用到，**必需**
        get_new_uptoken: false, //设置上传文件的时候是否每次都重新获取新的token
        container: container ? container : 'upLoadImagesContainer', //上传区域DOM ID，默认是browser_button的父元素，
        max_file_size: max_file_size, //最大文件体积限制
        max_retries: 3, //上传失败最大重试次数
        dragdrop: false, //开启可拖曳上传
        // drop_element: 'upLoadImagesContainer',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '0mb', //分块上传时，每片的体积
        auto_start: true, //选择文件后自动上传，若关闭需要自己绑定事件触发上传
        multi_selection: multiple ? true : false, //是否允许同时选择多文件
        force_direct: true,
        filters: {
          mime_types: [ //图片视频都支持
            {
              title: "Image files",
              extensions: "jpg,gif,png,jpeg,BMP,JPG,JPEG,PNG,GIF,mp4,3gp,mpeg,mavip4,mov,flv"
            }
          ]
        },
        resize: {
          // width: 100,
          // height: 100,
          // crop: true,
          // quality: 60,
          preserve_headers: false //解决转转问题
        },
        init: {
          // 文件添加进队列后,处理相关的事情
          'FilesAdded': function (up, files) {
            if (fileNumber) {
              if (files.length > fileNumber) {
                app.methods.showToastCenter("文件大于上限");
                isOver = true;
                //删除所有文件
                for (var j = 0; j < files.length; j++) {
                  uploaderLinlk.removeFile(files[j]);
                }
              } else {
                isOver = false;
              }
            }
          },
          // 每个文件上传前,处理相关的事情
          'BeforeUpload': function (up, file) {
            //app.methods.showToastCenter(file.size / (1024 ));
            if (!isOver) {
              common.loading(1);
              if (file.size > 2 * 1024 * 1024) {
                up.settings.resize.quality = 30;
              } else if (file.size > 1 * 1024 * 1024) {
                up.settings.resize.quality = 40;
              } else if (file.size > 0.5 * 1024 * 1024) {
                up.settings.resize.quality = 50;
              }
              up.settings.multipart_params.fileName = file.name
            } else {
              up.stop();
              common.loading(0)
            }
          },
          'UploadProgress': function (up, file) {
            // 每个文件上传时,处理相关的事情
          },
          'FileUploaded': function (up, file, info) {
            // 每个文件上传成功后,处理相关的事情
            var domain = up.getOption('domain');
            var res = eval('(' + info + ')');
            var sourceLink = uploadOnNginx ? res.data : domain + res.key; //获取上传文件的链接地址
            //do something
            if (successCb) {
              successCb(sourceLink, file);
            }
          },
          'Error': function (up, err, errTip) {
            // if(err.code != -200){//"HTTP 错误。"不提示

            // }
            app.methods.showToastCenter(errTip);
            common.loading(0);
          },
          'UploadComplete': function () {
            //队列文件处理完毕后,处理相关的事情
            // app.methods.showToastCenter("上传成功");
            common.loading(0);
          },
          'Key': function (up, file) {
            // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
            // 该配置必须要在 unique_names: false，save_key: false时才生效
            var fielLocal = file.name.split(".");
            var fielType = "." + fielLocal[fielLocal.length - 1];
            var currentTime = new Date().getTime() + Math.ceil(Math.random() * 99); //根据时间戳生成唯一标识
            var fielName_Local = currentTime;
            var key = "";
            var dirUrl = "app/";
            if (fileName) {
              key = dirUrl + fileName + fielType;
            } else {
              key = dirUrl + fielName_Local + fielType;
            }
            return key;
          }
        }
      });
    }, false)
  };


  //只能上传图片
  _self.upload_qiniu_heard = function (successCb, multiple, fileNumber, container, browse_button, maxSize, fileName, fileType) {
    Dao.qnToken({
      userName: userInfor.accountName,
      deviceId: appKeyObj.deviceId,
    }, function (token) {
      jQuery("#" + container ? container : "upLoadImagesContainer").off();
      jQuery("#" + (container ? container : "upLoadImagesContainer") + " .moxie-shim.moxie-shim-html5").remove();
      jQuery("#" + browse_button ? browse_button : "upLoadPickfiles").off();
      var filetypes = [];
      if (fileType) {
        filetypes = filetypes.concat(fileType);
      } else {
        filetypes.push({
          title: "ilinkPic",
          extensions: "*"
        });
      }
      var max_file_size = "100mb";
      if (maxSize) {
        max_file_size = maxSize;
      }
      var isOver = false;
      uploaderLinlk = Qiniu.uploader({
        runtimes: 'html5,flash,html4', //上传模式,依次退化
        browse_button: browse_button ? browse_button : 'upLoadPickfiles', //上传选择的点选按钮，**必需**
        uptoken: token, //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        domain: QINIUPATH, //bucket 域名，下载资源时用到，**必需**
        get_new_uptoken: false, //设置上传文件的时候是否每次都重新获取新的token
        container: container ? container : 'upLoadImagesContainer', //上传区域DOM ID，默认是browser_button的父元素，
        max_file_size: max_file_size, //最大文件体积限制
        max_retries: 3, //上传失败最大重试次数
        dragdrop: false, //开启可拖曳上传
        // drop_element: 'upLoadImagesContainer',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '0mb', //分块上传时，每片的体积
        auto_start: true, //选择文件后自动上传，若关闭需要自己绑定事件触发上传
        multi_selection: multiple ? true : false, //是否允许同时选择多文件
        force_direct: true,
        filters: {
          mime_types: [ //图片支持
            {
              title: "Image files",
              extensions: "jpg,gif,png,jpeg,BMP,JPG,JPEG,PNG,GIF"
            }
          ]
        },
        resize: {
          // width: 100,
          // height: 100,
          // crop: true,
          // quality: 60,
          preserve_headers: false //解决转转问题
        },
        init: {
          // 文件添加进队列后,处理相关的事情
          'FilesAdded': function (up, files) {
            if (fileNumber) {
              if (files.length > fileNumber) {
                app.methods.showToastCenter("文件大于上限");
                isOver = true;
                //删除所有文件
                for (var j = 0; j < files.length; j++) {
                  uploaderLinlk.removeFile(files[j]);
                }
              } else {
                isOver = false;
              }
            }
          },
          // 每个文件上传前,处理相关的事情
          'BeforeUpload': function (up, file) {
            //app.methods.showToastCenter(file.size / (1024 ));
            if (!isOver) {
              common.loading(1);
              if (file.size > 2 * 1024 * 1024) {
                up.settings.resize.quality = 30;
              } else if (file.size > 1 * 1024 * 1024) {
                up.settings.resize.quality = 40;
              } else if (file.size > 0.5 * 1024 * 1024) {
                up.settings.resize.quality = 50;
              }
              up.settings.multipart_params.fileName = file.name
            } else {
              up.stop();
              common.loading(0)
            }
          },
          'UploadProgress': function (up, file) {
            // 每个文件上传时,处理相关的事情
          },
          'FileUploaded': function (up, file, info) {
            // 每个文件上传成功后,处理相关的事情
            var domain = up.getOption('domain');
            var res = eval('(' + info + ')');
            var sourceLink = uploadOnNginx ? res.data : domain + res.key; //获取上传文件的链接地址
            //do something
            if (successCb) {
              successCb(sourceLink, file);
            }
          },
          'Error': function (up, err, errTip) {
            // if(err.code != -200){//"HTTP 错误。"不提示

            // }
            app.methods.showToastCenter("仅支持上传图片！");
            common.loading(0);
          },
          'UploadComplete': function () {
            //队列文件处理完毕后,处理相关的事情
            // app.methods.showToastCenter("上传成功");
            common.loading(0);
          },
          'Key': function (up, file) {
            // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
            // 该配置必须要在 unique_names: false，save_key: false时才生效
            var fielLocal = file.name.split(".");
            var fielType = "." + fielLocal[fielLocal.length - 1];
            var currentTime = new Date().getTime() + Math.ceil(Math.random() * 99); //根据时间戳生成唯一标识
            var fielName_Local = currentTime;
            var key = "";
            var dirUrl = "app/";
            if (fileName) {
              key = dirUrl + fileName + fielType;
            } else {
              key = dirUrl + fielName_Local + fielType;
            }
            return key;
          }
        }
      });
    }, false)
  };

  //签到
  _self.upload_qiniu_signIn = function (successCb, multiple, fileNumber, container, browse_button, maxSize, fileName, fileType) {
    Dao.qnToken({
      userName: userInfor.accountName,
      deviceId: appKeyObj.deviceId,
    }, function (token) {
      jQuery("#" + container ? container : "upLoadImagesContainer").off();
      jQuery("#" + (container ? container : "upLoadImagesContainer") + " .moxie-shim.moxie-shim-html5").remove();
      jQuery("#" + browse_button ? browse_button : "upLoadPickfilesSign").off();
      var filetypes = [];
      if (fileType) {
        filetypes = filetypes.concat(fileType);
      } else {
        filetypes.push({
          title: "ilinkPic",
          extensions: "*"
        });
      }
      var max_file_size = "100mb";
      if (maxSize) {
        max_file_size = maxSize;
      }
      var isOver = false;
      uploaderLinlk = Qiniu.uploader({
        runtimes: 'html5,flash,html4', //上传模式,依次退化
        browse_button: browse_button ? browse_button : 'upLoadPickfilesSign', //上传选择的点选按钮，**必需**
        uptoken: token, //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        domain: QINIUPATH, //bucket 域名，下载资源时用到，**必需**
        get_new_uptoken: false, //设置上传文件的时候是否每次都重新获取新的token
        container: container ? container : 'upLoadImagesContainer', //上传区域DOM ID，默认是browser_button的父元素，
        max_file_size: max_file_size, //最大文件体积限制
        max_retries: 3, //上传失败最大重试次数
        dragdrop: false, //开启可拖曳上传
        // drop_element: 'upLoadImagesContainer',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '0mb', //分块上传时，每片的体积
        auto_start: true, //选择文件后自动上传，若关闭需要自己绑定事件触发上传
        multi_selection: multiple ? true : false, //是否允许同时选择多文件
        force_direct: true,
        filters: {
          mime_types: [ //图片视频都支持
            {
              title: "Image files",
              extensions: "jpg,gif,png,jpeg,BMP,JPG,JPEG,PNG,GIF,mp4,3gp,mpeg,mavip4,mov,flv"
            }
          ]
        },
        resize: {
          // width: 100,
          // height: 100,
          // crop: true,
          // quality: 60,
          preserve_headers: false //解决转转问题
        },
        init: {
          // 文件添加进队列后,处理相关的事情
          'FilesAdded': function (up, files) {
            if (fileNumber) {
              if (files.length > fileNumber) {
                app.methods.showToastCenter("文件大于上限");
                isOver = true;
                //删除所有文件
                for (var j = 0; j < files.length; j++) {
                  uploaderLinlk.removeFile(files[j]);
                }
              } else {
                isOver = false;
              }
            }
          },
          // 每个文件上传前,处理相关的事情
          'BeforeUpload': function (up, file) {
            //app.methods.showToastCenter(file.size / (1024 ));
            if (!isOver) {
              common.loading(1);
              if (file.size > 2 * 1024 * 1024) {
                up.settings.resize.quality = 30;
              } else if (file.size > 1 * 1024 * 1024) {
                up.settings.resize.quality = 40;
              } else if (file.size > 0.5 * 1024 * 1024) {
                up.settings.resize.quality = 50;
              }
              up.settings.multipart_params.fileName = file.name
            } else {
              up.stop();
              common.loading(0)
            }
          },
          'UploadProgress': function (up, file) {
            // 每个文件上传时,处理相关的事情
          },
          'FileUploaded': function (up, file, info) {
            // 每个文件上传成功后,处理相关的事情
            var domain = up.getOption('domain');
            var res = eval('(' + info + ')');
            var sourceLink = uploadOnNginx ? res.data : domain + res.key; //获取上传文件的链接地址
            //do something
            if (successCb) {
              successCb(sourceLink, file);
            }
          },
          'Error': function (up, err, errTip) {
            // if(err.code != -200){//"HTTP 错误。"不提示

            // }
            app.methods.showToastCenter(errTip);
            common.loading(0);
          },
          'UploadComplete': function () {
            //队列文件处理完毕后,处理相关的事情
            // app.methods.showToastCenter("上传成功");
            common.loading(0);
          },
          'Key': function (up, file) {
            // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
            // 该配置必须要在 unique_names: false，save_key: false时才生效
            var fielLocal = file.name.split(".");
            var fielType = "." + fielLocal[fielLocal.length - 1];
            var currentTime = new Date().getTime() + Math.ceil(Math.random() * 99); //根据时间戳生成唯一标识
            var fielName_Local = currentTime;
            var key = "";
            var dirUrl = "app/";
            if (fileName) {
              key = dirUrl + fileName + fielType;
            } else {
              key = dirUrl + fielName_Local + fielType;
            }
            return key;
          }
        }
      });
    }, false)
  };
  //上传文件
  _self.upload_qiniu_Out = function (successCb, multiple, fileNumber, container, browse_button, maxSize, fileName, fileType) {
    Dao.qnToken({
      userName: userInfor.accountName,
      deviceId: appKeyObj.deviceId,
    }, function (token) {
      jQuery("#" + container ? container : "upLoadImagesContainerOut").off();
      jQuery("#" + (container ? container : "upLoadImagesContainerOut") + " .moxie-shim.moxie-shim-html5").remove();
      jQuery("#" + browse_button ? browse_button : "upLoadPickfilesOut").off();
      var filetypes = [];
      if (fileType) {
        filetypes = filetypes.concat(fileType);
      } else {
        filetypes.push({
          title: "ilinkPic",
          extensions: "*"
        });
      }
      var max_file_size = "100mb";
      if (maxSize) {
        max_file_size = maxSize;
      }
      var isOver = false;
      uploaderLinlk = Qiniu.uploader({
        runtimes: 'html5,flash,html4', //上传模式,依次退化
        browse_button: browse_button ? browse_button : 'upLoadPickfilesOut', //上传选择的点选按钮，**必需**
        uptoken: token, //若未指定uptoken_url,则必须指定 uptoken ,uptoken由其他程序生成
        domain: QINIUPATH, //bucket 域名，下载资源时用到，**必需**
        get_new_uptoken: false, //设置上传文件的时候是否每次都重新获取新的token
        container: container ? container : 'upLoadImagesContainerOut', //上传区域DOM ID，默认是browser_button的父元素，
        max_file_size: max_file_size, //最大文件体积限制
        max_retries: 3, //上传失败最大重试次数
        dragdrop: false, //开启可拖曳上传
        // drop_element: 'upLoadImagesContainerOut',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
        chunk_size: '0mb', //分块上传时，每片的体积
        auto_start: true, //选择文件后自动上传，若关闭需要自己绑定事件触发上传
        multi_selection: multiple ? true : false, //是否允许同时选择多文件
        force_direct: true,
        filters: {
          mime_types: [ //图片视频都支持
            {
              title: "Image files",
              extensions: "jpg,gif,png,jpeg,BMP,JPG,JPEG,PNG,GIF,mp4,3gp,mpeg,mavip4,mov,flv"
            }
          ]
        },
        resize: {
          // width: 100,
          // height: 100,
          // crop: true,
          // quality: 60,
          preserve_headers: false //解决转转问题
        },
        init: {
          // 文件添加进队列后,处理相关的事情
          'FilesAdded': function (up, files) {
            if (fileNumber) {
              if (files.length > fileNumber) {
                app.methods.showToastCenter("文件大于上限");
                isOver = true;
                //删除所有文件
                for (var j = 0; j < files.length; j++) {
                  uploaderLinlk.removeFile(files[j]);
                }
              } else {
                isOver = false;
              }
            }
          },
          // 每个文件上传前,处理相关的事情
          'BeforeUpload': function (up, file) {
            //app.methods.showToastCenter(file.size / (1024 ));
            if (!isOver) {
              common.loading(1);
              if (file.size > 2 * 1024 * 1024) {
                up.settings.resize.quality = 30;
              } else if (file.size > 1 * 1024 * 1024) {
                up.settings.resize.quality = 40;
              } else if (file.size > 0.5 * 1024 * 1024) {
                up.settings.resize.quality = 50;
              }
              up.settings.multipart_params.fileName = file.name
            } else {
              up.stop();
              common.loading(0)
            }
          },
          'UploadProgress': function (up, file) {
            // 每个文件上传时,处理相关的事情
          },
          'FileUploaded': function (up, file, info) {
            // 每个文件上传成功后,处理相关的事情
            var domain = up.getOption('domain');
            var res = eval('(' + info + ')');
            var sourceLink = uploadOnNginx ? res.data : domain + res.key; //获取上传文件的链接地址
            //do something
            if (successCb) {
              successCb(sourceLink, file);
            }
          },
          'Error': function (up, err, errTip) {
            // if(err.code != -200){//"HTTP 错误。"不提示

            // }
            app.methods.showToastCenter(errTip);
            common.loading(0);
          },
          'UploadComplete': function () {
            //队列文件处理完毕后,处理相关的事情
            // app.methods.showToastCenter("上传成功");
            common.loading(0);
          },
          'Key': function (up, file) {
            // 若想在前端对每个文件的key进行个性化处理，可以配置该函数
            // 该配置必须要在 unique_names: false，save_key: false时才生效
            var fielLocal = file.name.split(".");
            var fielType = "." + fielLocal[fielLocal.length - 1];
            var currentTime = new Date().getTime() + Math.ceil(Math.random() * 99); //根据时间戳生成唯一标识
            var fielName_Local = currentTime;
            var key = "";
            var dirUrl = "app/";
            if (fileName) {
              key = dirUrl + fileName + fielType;
            } else {
              key = dirUrl + fielName_Local + fielType;
            }
            return key;
          }
        }
      });
    }, false)
  };
  //离线上传文件
  _self.upload_qiniu_offLine = function (successCb, multiple, fileNumber, container, browse_button, maxSize, fileName, fileType) {
    jQuery("#" + container ? container : "upLoadImagesContainer").off();
    jQuery("#" + (container ? container : "upLoadImagesContainer") + " .moxie-shim.moxie-shim-html5").remove();
    jQuery("#" + browse_button ? browse_button : "upLoadPickfiles").off();
    var filetypes = [];
    if (fileType) {
      filetypes = filetypes.concat(fileType);
    } else {
      filetypes.push({
        title: "ilinkPic",
        extensions: "*"
      });
    }
    var max_file_size = "100mb";
    if (maxSize) {
      max_file_size = maxSize;
    }
    var isOver = false;
    uploaderLinlk = new plupload.Uploader({
      runtimes: 'html5,flash,html4', //上传模式,依次退化
      browse_button: browse_button ? browse_button : 'upLoadPickfiles', //上传选择的点选按钮，**必需**
      container: container ? container : 'upLoadImagesContainer', //上传区域DOM ID，默认是browser_button的父元素，
      max_file_size: max_file_size, //最大文件体积限制
      max_retries: 3, //上传失败最大重试次数
      chunk_size: '0mb', //分块上传时，每片的体积
      url: 'upload.php',
      // auto_start: true,                 //选择文件后自动上传，若关闭需要自己绑定事件触发上传
      multi_selection: multiple ? true : false, //是否允许同时选择多文件
      force_direct: true,
      filters: {
        mime_types: [ //只允许上传图片
          {
            title: "Image files",
            extensions: "jpg,gif,png,jpeg,BMP,JPG,JPEG,PNG,GIF"
          }
        ]
      },
      resize: {
        preserve_headers: false //解决转转问题
      },
      init: {
        // 文件添加进队列后,处理相关的事情
        'FilesAdded': function (up, files) { },
        'FileFiltered': function (up, file) {
          if (fileNumber) {
            var preloader = new mOxie.Image();
            preloader.onload = function () {
              var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
              file.imgsrc = imgsrc;
              preloader.destroy();
              preloader = null;
              if (successCb) {
                successCb(file.name, file);
              }
            };
            preloader.load(file.getSource());
          }
        },
        'Error': function (up, err, errTip) {
          app.methods.showToastCenter(errTip);
          common.loading(0);
        },
        'UploadComplete': function () {
          //队列文件处理完毕后,处理相关的事情
          common.loading(0);
        },
      }
    }, false)
    uploaderLinlk.init();
  };

  //直接上传
  _self.putb64OrBolb = function (originalData, callback) {
    if (QINIUPATH == '/ilink-file/') { //一体机模式
      Dao.uploadBase64({
        base64: encodeURIComponent(originalData.replace(/^.*?base64,/, '')),
        fileName: new Date().getTime() + '.' + originalData.split(';base64,')[0].replace('data:image/', '')
      }, function (res) {
        callback && callback(originalData, res);
      })
    } else {
      Dao.qnToken({
        userName: userInfor.accountName,
        deviceId: appKeyObj.deviceId,
      }, function (token) {
        var data = originalData.replace(/^.*?base64,/, '')
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4) {
            callback && callback(originalData, QINIUPATH + JSON.parse(xhr.responseText).key);
          }
        }
        xhr.open("POST", "http://upload.qiniup.com/putb64/-1", true);
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.setRequestHeader("Authorization", "UpToken " + token);
        xhr.send(data);
      });
    }
  }

  var getCharCount = (str, char) => {
    var regex = new RegExp(char, 'g'); // 使用g表示整个字符串都要匹配
    var result = str.match(regex); //match方法可在字符串内检索指定的值，或找到一个或多个正则表达式的匹配。
    var count = !result ? 0 : result.length;
    return count;
  }

  //拦截param，更换图片为七牛云链接
  _self.multiUpload = function (mulParam, callback) {
    let param = mulParam
    if (param.indexOf('data:image') < 0) {
      callback && callback(param);
      return
    }
    var imageCount = getCharCount(param, 'data:image')
    var base64Strs = []
    try {
      var subStr = param + ''
      for (let index = 0; index < imageCount; index++) {
        subStr = subStr.substr(subStr.indexOf('data:image'));
        base64Strs.push(subStr.substr(0, (subStr.indexOf('___data:image') > -1) ? subStr.indexOf('___data:image') : subStr.indexOf('\\')))
        subStr = subStr.replace('data:image', '')
      }
      param = encodeURIComponent(param)
      for (let index = 0; index < imageCount; index++) {
        _self.putb64OrBolb(base64Strs[index], function (originalData, url) {
          param = param.replace(encodeURIComponent(originalData), url);
          imageCount--;
          if (imageCount == 0) {
            // 替换多张图片分隔符"___"
            param = decodeURIComponent(param).replace(/___/g, ',')
            callback && callback(param);
          }
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  //判断移动设备
  //设备类型 1 ios  2 android
  _self.checkMobile = function () {
    var u = navigator.userAgent;
    if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 || u.indexOf('Adr') > -1) { //安卓手机
      return 2;
    } else if (u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1 || u.indexOf("iOS") > -1) { //苹果手机
      return 1;
    } else if (u.indexOf('Windows Phone') > -1) { //winphone手机 
      return 0;
    } else {
      return 99;
    }
  }
  //去除数组中的空元素
  _self.removeEmptyArrayEle = function (arr) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == "") {
        arr.splice(i, 1);
        i = i - 1; // i - 1 ,因为空元素在数组下标 2 位置，删除空之后，后面的元素要向前补位，
        // 这样才能真正去掉空元素,觉得这句可以删掉的连续为空试试，然后思考其中逻辑
      }
    }
    return arr;
  };

  /*
   ** randomWord 产生任意长度随机字母数字组合
   ** randomFlag-是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
   ** xuanfeng 2014-08-28
   */

  _self.randomWord = function (randomFlag, min, max) {
    var str = "",
      range = min,
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

    // 随机产生
    if (randomFlag) {
      range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
      pos = Math.round(Math.random() * (arr.length - 1));
      str += arr[pos];
    }
    return str;
  }
  //获取评分
  _self.getScore = function (score) {
    var fixScore = parseFloat(parseFloat(score).toFixed(1));
    if (79.9 < fixScore && fixScore < 89.9) { //风险
      return 10;
    } else if (fixScore < 80) { //高危
      return 20;
    } else { //安全
      return 30;
    }
  }

  /**
   * @desc Loading
   * @param {Boolean} startOrEnd 
   */
  _self.loading = function (startOrEnd) {
    //app.dialog.preloader( msg==null ? "玩命加载中..." :msg);
    if (startOrEnd) {
      app.preloader.show();
      setTimeout(function () {
        app.preloader.hide();
      }, 10 * 1000);
    } else {
      app.preloader.hide();
    }
  }
  //判断时间戳是否是今天 是今天显示hh:mm  之前显示MM-DD hh:mm
  _self.getTimeStrIsToday = function (timeStr) {
    if (new Date(timeStr).toDateString() === new Date().toDateString()) {
      //今天
      return moment(timeStr).format('HH:mm');
    } else if (new Date(timeStr) < new Date()) {
      //之前
      return moment(timeStr).format('MM-DD HH:mm');
    }
  }
  //判断时间戳是否是今天 是今天 true  之前显示false
  _self.judgeTimeIsToday = function (timeStr) {
    if (new Date(timeStr).toDateString() === new Date().toDateString()) {
      //今天
      return true;
    } else if (new Date(timeStr) < new Date()) {
      //之前
      return false;
    }
  }

  //秒转时间
  _self.getSecondsFormat = function (s) {
    var timeStr = "";
    var day = Math.floor(s / (24 * 3600)); // Math.floor()向下取整
    if (day > 0) {
      return day + "天";
    }
    var hour = Math.floor((s - day * 24 * 3600) / 3600);
    if (hour > 0) {
      timeStr += hour + "时";
      return timeStr;
    }
    var minute = Math.floor((s - day * 24 * 3600 - hour * 3600) / 60);
    if (minute > 0) {
      timeStr += minute + "分";
      return timeStr;
    }
    var second = Math.floor(s - day * 24 * 3600 - hour * 3600 - minute * 60);
    if (60 > s) {
      timeStr += second + "秒";
      return timeStr;
    }
  }
  //秒转时间 61 1分钟1秒
  _self.formatDuring = function (s) {
    var days = parseInt(s / (60 * 60 * 24));
    var hours = parseInt((s % (60 * 60 * 24)) / (60 * 60));
    var minutes = parseInt((s % (60 * 60)) / (60));
    var second = s % 60;
    return days != 0 ? days + '天' : '' + hours != 0 ? hours + '小时' : '' + minutes != 0 ? minutes + '分钟' : '' + second + '秒';
  }
  //var timeArray = [{"id":"1","name":"09月28日"}];
  //type 0:年 1:年月 2：月日
  _self.getTimeArray = function (type) {
    var num = null;
    var canData = [];
    if (type == 0) {
      num = 10;
    } else if (type == 1) {
      num = 30;
    } else {
      num = 30;
    }
    for (var i = 0; i < num; i++) {
      var data = "";
      if (type == 0) {
        data = moment().subtract(i, 'years').format("YYYY年");
      } else if (type == 1) {
        data = moment().subtract(i, 'months').format("YYYY年MM月");
      } else {
        data = moment().subtract(i, 'days').format("YYYY年MM月DD日");
      }
      var obj = {
        id: i + 1,
        name: data
      }
      canData.push(obj);
    }
    return canData;
  }




  //09月09日 转完成时间字符串
  _self.getMMDDToyyyymmddhhmmss = function (time) {
    var timeArray = time.split('月');
    var m = timeArray[0]
    var d = timeArray[1].split('日')[0];
    return new Date().getFullYear() + '-' + m + '-' + d + ' ';
  }

  //js小数相相乘失去精度问题解析详解（最优方案）
  _self.mul = function (arg1, arg2) {
    var m = 0,
      s1 = arg1.toString(),
      s2 = arg2.toString();
    try {
      m += s1.split(".")[1].length;
    } catch (e) { }
    try {
      m += s2.split(".")[1].length;
    } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  };

  //数组
  //js sort只会按照数字第一位排序，所以自定义排序函数
  //调用方法 arr.sort(common.sortNumber);
  _self.sortNumber = function (a, b, reverse) {
    if (reverse) {
      return b - a;
    }
    return a - b;
  }
  //数组对象方法排序:
  _self.sortByKey = function (array, key, reverse) {
    if (array && array.length > 0) {
      return array.sort(function (a, b) {
        var x = parseFloat(a[key]);
        var y = parseFloat(b[key]);
        if (reverse) {
          return ((y < x) ? -1 : ((y > x) ? 1 : 0));
        }
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
      });
    }
  }

  //判断图片是否存在
  _self.checkImgExists = function (imgurl, success, err) {
    var ImgObj = new Image(); //判断图片是否存在  
    ImgObj.onload = function () {
      success && success(ImgObj)
    }
    ImgObj.onerror = function () {
      err && err(ImgObj)
    }
    ImgObj.src = imgurl;
  }

  //获取输入框对象列表的值逗号拼接
  _self.getObjValJoin = function (arr) {
    var ids = "";
    if (arr != null) {
      for (var i = 0; i < arr.length; i++) {
        var id = $(arr[i]).val();
        if (i < arr.length - 1) {
          id = id + ",";
        }
        ids += id;
      }
    }
    return ids;
  }

  //计算时差
  _self.getTimeDifference = function (start, end) {
    if (start && end) {
      let a = moment(start);
      let b = moment(end);
      let tempTime = moment.duration(b - a);
      return tempTime._data;
    }
  }

  /* 
  给上传的图片加上时间水印 
  //产品说要拍照的时候打上水印，而不是上传后。暂时搁置
  七牛文档：https://developer.qiniu.com/dora/api/1316/image-watermarking-processing-watermark
  */
  //隐患、维保等
  _self.addWatermark = function (oldUrl, text) {
    return oldUrl
    /* return Qiniu.pipeline([{
      fop: 'watermark',
      mode: 2,
      text: text?text:_self.getNowtime(),
      font:'微软雅黑',
      fontsize:'400',
      fill:'#000000',
      dissolve: 100,
      gravity: 'SouthEast',
      dx: 20,
      dy: 20
    }],oldUrl.replace(QINIUPATH,'')) */
  }

  return _self;
})(window.common || {});

function GetQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return unescape(r[2]);
  return null
}